package meb

import (
	"context"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/mosongcc/gotool/gtime"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	"log/slog"
	"net/http"
	"vitepress-serve/internal/common/hgin"
	"vitepress-serve/internal/model"
)

// PATH_WXPAY_NOTIFY mchid=微信商户号  order_id=订单号
const PATH_WXPAY_NOTIFY = "/vpapi/meb/wxpaynotify/:mchid/:order_id"

// WxpayNotify 微信支付通知
func (ctl *Controller) WxpayNotify(ctx *gin.Context) (err error) {
	var (
		mchid = ctx.Param("mchid") // 微信商户号
		//orderId = ctx.Param("order_id")
	)
	handler, err := ctl.WxpayService.RSANotifyHandler(mchid)
	if err != nil {
		return
	}
	var t *payments.Transaction
	if _, err = handler.ParseNotifyRequest(context.Background(), ctx.Request, &t); err != nil {
		return
	}
	err = wxpaySuccess(ctl, t)
	if err != nil {
		return
	}

	//订单执行发货
	go func() {
		_, err2 := ctl.OrderService.FinishVip(*t.OutTradeNo)
		if err2 != nil {
			slog.Info(fmt.Sprintf("微信支付通知 订单发货失败 orderId: %s errMsg: %s", *t.OutTradeNo, err2.Error()))
			return
		}
	}()

	resBody := `{"code":"SUCCESS","message":"ok"}`
	ctx.Set(hgin.CtxSetResBody, resBody)
	ctx.String(http.StatusOK, resBody)
	return
}

// 订单微信支付结果更新
func wxpaySuccess(ctl *Controller, t *payments.Transaction) (err error) {
	if *t.TradeState != "SUCCESS" {
		err = errors.New("WXPAY_" + *t.TradeState + ":" + *t.TradeStateDesc)
		return
	}
	// 支付成功
	var order = model.Order{
		OrderId:  *t.OutTradeNo,
		Status:   model.ORDER_STATUS_PAID,
		PayNo:    *t.TransactionId,
		PayMchid: *t.Mchid,
		PayTime:  gtime.ParseRFC3339(*t.SuccessTime).Format(gtime.LayoutT14),
		Mtime:    gtime.NowF14(),
	}
	if err = ctl.db.Model(&order).Where("order_id = ? and status = ?", order.OrderId, model.ORDER_STATUS_PENDING).Updates(order).Error; err != nil {
		return
	}
	return
}
